namespace AbpPlus.Commands
{
	using Abp.Domain.Uow;

	using AbpPlus.Bus;
	using AbpPlus.Events;

	using MediatR;

	/// <summary>
	/// The command handler.
	/// </summary>
	public class CommandHandler
	{
		/// <summary>
		/// The _uow.
		/// </summary>
		private readonly IUnitOfWorkManager _uow;

		/// <summary>
		/// The _bus.
		/// </summary>
		private readonly IMediatorHandler _bus;
		
		/// <summary>
		/// The _notifications.
		/// </summary>
		private readonly DomainNotificationHandler _notifications;
		
		/// <summary>
		/// Initializes a new instance of the <see cref="CommandHandler"/> class.
		/// </summary>
		/// <param name="uow">
		/// The uow.
		/// </param>
		/// <param name="bus">
		/// The bus.
		/// </param>
		/// <param name="notifications">
		/// The notifications.
		/// </param>
		public CommandHandler(IUnitOfWorkManager uow, IMediatorHandler bus, INotificationHandler<DomainNotification> notifications)
		{
			this._uow = uow;
			this._notifications = (DomainNotificationHandler)notifications;
			this._bus = bus;
		}

		/// <summary>
		/// The commit.
		/// </summary>
		/// <returns>
		/// The <see cref="bool"/>.
		/// </returns>
		public bool Commit()
		{
			if (this._notifications.HasNotifications())
			{
				return false;
			}

			this._uow.Current.SaveChanges(); 
			
			this._bus.RaiseEvent(new DomainNotification("Commit", "We had a problem during saving your data."));
			return false;
		}
		
		/// <summary>
		/// The notify validation errors.
		/// </summary>
		/// <param name="message">
		/// The message.
		/// </param>
		protected void NotifyValidationErrors(Command message)
		{
			foreach (var error in message.ValidationResult.Errors)
			{
				this._bus.RaiseEvent(new DomainNotification(message.MessageType, error.ErrorMessage));
			}
		}
	}
}